// JavaScript Document
'usr strict';
$(function() {
    rowCount_nil_day = 0, //行数默认3行
	rowCount_nil_num = 0,
	rowCount_baina_day = 0,
	rowCount_baina_num = 0,
	rowCount_buy_day = 0,
	rowCount_buy_num = 0,
	rowCount_paras = 0,
    //searchForm: 表单搜索
    window.searchForm = {
        before:function(callback){
            loadpage.before(callback, '搜索中，请稍后...');
        },
        call: function(error, success) {
            var $this = $(this);
            loadpage.close(function() {
                if (error) {
                    $.error(error);
                } else {
                    var container = $($this.attr('container'));
                    var top = $this.attr('top') || true;
                    if (top !== 'false') {
                        $('body').animate({ scrollTop: 0 }, 500, function() {
                            container.fadeOut(function() {
                                $(this).html(success).fadeIn();
                            });
                        });
                    } else {
                        container.fadeOut(function() {
                            $(this).html(success).fadeIn();
                        });
                    }
                }
            });
        },
    },
	// form_submit: 表单提交
    window.form_submit = {
        before: function(callback) {
            loadpage.before(callback, '正在提交中，请稍后...');
        },
        call: function(error, success) {
            var $this = $(this);
            loadpage.close(function() {
                if (error) {
                    $.error(error);
                } else {
                    var container = $($this.attr('container'));
                    var top = $this.attr('top') || true;
                    if (top !== 'false') {
                        $('body').animate({ scrollTop: 0 }, 500, function() {
                            container.fadeOut(function() {
                                $(this).html(success).fadeIn();
                            });
                        });
                    } else {
                        container.fadeOut(function() {
                            $(this).html(success).fadeIn();
                        });
                    }
                }
            });
        },
    };
        window.app = {
			delParasRow : function(rowIndex, rowcountname){
				$(rowIndex).remove();
                rowCount_paras--;
			},
			addParaRow : function(inputname,idname,htmtid,rowcountname){
				rowCount_paras++;
                var rowcount = rowCount_paras;
				var newRow = '<dl id="' + idname + rowcount + '"><dt>规则参数' + rowcount + '：</dt>';
                newRow += '<dd><input type="text" name="' + inputname + '_name" class="mint" value="" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_value" class="mint" value="" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_icon" id="paras_icon_'+rowcount+'" class="int" value="#" style="width:320px;" /></dd><dd><input type="button" name="upload_paras_'+rowcount+'" id="upload_paras_'+rowcount+'" value="选图"></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_nums" class="int" value="1" /></dd>';
                newRow += '</dd><dd class="t"><a href="#" onclick=window.app.delParasRow("#' + idname + rowcount + '","' + rowcountname + '")>删除</a></dd>';
				newRow += '<dd><input type="button" onClick="window.app.producticoncorp_gg('+rowcount+')" id="markeimagescorp" value="缩图" /></a></dd>';
                newRow += '</dl>';
				
				newRow += '<script>editor("#upload_paras_'+rowcount+'").click(function () {';
            	newRow += 'editorname.loadPlugin("image", function () {';
                newRow += 'editorname.plugin.imageDialog({';
                newRow += 'imageUrl: editor("#paras_icon_'+rowcount+'").val(),';
                newRow += 'clickFn: function (url, title, width, height, border, align) {';
                newRow += 'editor("#paras_icon_'+rowcount+'").val(url);';
                newRow += 'editorname.hideDialog();';
                newRow += '}';
                newRow += '});';
            	newRow += '});';
        		newRow += '});</script>';

                $(htmtid).append(newRow);
			},
            addPresRow: function(inputname, idname, htmtid, rowcountname) {
                switch (rowcountname) {
                    case 'rowCount_nil_num':
                        rowCount_nil_num++;
                        rowcount = rowCount_nil_num;
                        break;
                    case 'rowCount_nil_day':
                        rowCount_nil_day++;
                        rowcount = rowCount_nil_day;
                        break;
                    case 'rowCount_baina_day':
                        rowCount_baina_day++;
                        rowcount = rowCount_baina_day;
                        break;
                    case 'rowCount_baina_num':
                        rowCount_baina_num++;
                        rowcount = rowCount_baina_num;
                        break;
                    case 'rowCount_buy_day':
                        rowCount_buy_day++;
                        rowcount = rowCount_buy_day;
                        break;
                }
                var newRow = '<dl id="' + idname + rowcount + '"><dt>阶梯优惠' + rowcount + '：</dt>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_nums" class="mint" value="0" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_coin" class="mint" value="0" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_pres" class="mint" value="0" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_core" class="mint" value="0" /></dd>';
                newRow += '</dd><dd class="t"><a href="#" onclick=window.app.delPresRow("#' + idname + rowcount + '","' + rowcountname + '")>删除</a></dd>';
                //newRow+='<dd><input type="text" name="'+inputname+'_step_rate" class="mint" value="0" /></dd>';
                //newRow+='<dd><a href="#" onclick=window.app.calStep("#'+idname+rowcount+'")>计算</a></dd>';
                newRow += '</dl>';
                $(htmtid).append(newRow);

            },
            addPresRowNum: function(inputname, idname, htmtid, rowcountname) {
                switch (rowcountname) {
                    case 'rowCount_nil_num':
                        rowCount_nil_num++;
                        rowcount = rowCount_nil_num;
                        break;
                    case 'rowCount_nil_day':
                        rowCount_nil_day++;
                        rowcount = rowCount_nil_day;
                        break;
                    case 'rowCount_baina_day':
                        rowCount_baina_day++;
                        rowcount = rowCount_baina_day;
                        break;
                    case 'rowCount_baina_num':
                        rowCount_baina_num++;
                        rowcount = rowCount_baina_num;
                        break;
                    case 'rowCount_buy_day':
                        rowCount_buy_day++;
                        rowcount = rowCount_buy_day;
                        break;
                    case 'rowCount_buy_num':
                        rowCount_buy_num++;
                        rowcount = rowCount_buy_num;
                        break;
                    case 'rowCount_buy_num':
                        rowCount_buy_num++;
                        rowcount = rowCount_buy_num;
                        break;
                }
                var newRow = '<dl id="' + idname + rowcount + '"><dt>阶梯优惠' + rowcount + '：</dt>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_nums" class="mint" value="0" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_pres" class="mint" value="0" /></dd>';
                newRow += '<dd><input type="text" name="' + inputname + '_step_core" class="mint" value="0" /></dd>';
                newRow += '</dd><dd class="t"><a href="#" onclick=window.app.delPresRow("#' + idname + rowcount + '","' + rowcount + '")>删除</a></dd></dl>';
                $(htmtid).append(newRow);

            },
            //删除行  
            delPresRow: function(rowIndex, rowcountname) {
                $(rowIndex).remove();
                switch (rowcountname) {
                    case 'rowCount_nil_num':
                        rowCount_nil_num--;
                        break;
                    case 'rowCount_nil_day':
                        rowCount_nil_day--;
                        break;
                    case 'rowCount_baina_day':
                        rowCount_baina_day--;
                        break;
                    case 'rowCount_baina_num':
                        rowCount_baina_num--;
                        break;
                    case 'rowCount_buy_day':
                        rowCount_buy_day--;
                        break;
                    case 'rowCount_buy_num':
                        rowCount_buy_num--;
                        break;
                    case 'rowCount_buy_num':
                        rowCount_buy_num--;
                        break;
                }
            },
            steplistvalue: function(fieldname) {
                var result = $("input[name='" + fieldname + "']").map(function() {
                    return $(this).val();
                }).get();
                return result;
            },
            product_add_submit: function(formid) {
                var nil_day_step_nums = window.app.steplistvalue('nil_day_step_nums');
                var nil_day_step_coin = window.app.steplistvalue('nil_day_step_coin');
                var nil_day_step_pres = window.app.steplistvalue('nil_day_step_pres');
                var nil_day_step_core = window.app.steplistvalue('nil_day_step_core');
                var nil_num_step_nums = window.app.steplistvalue('nil_num_step_nums');
                var nil_num_step_pres = window.app.steplistvalue('nil_num_step_pres');
                var nil_num_step_core = window.app.steplistvalue('nil_num_step_core');
                var buy_num_step_nums = window.app.steplistvalue('buy_num_step_nums');
                var buy_num_step_pres = window.app.steplistvalue('buy_num_step_pres');
                var buy_num_step_core = window.app.steplistvalue('buy_num_step_core');
                var baina_day_step_nums = window.app.steplistvalue('baina_day_step_nums');
                var baina_day_step_coin = window.app.steplistvalue('baina_day_step_coin');
                var baina_day_step_pres = window.app.steplistvalue('baina_day_step_pres');
                var baina_day_step_core = window.app.steplistvalue('baina_day_step_core');
                var baina_num_step_nums = window.app.steplistvalue('baina_num_step_nums');
                var baina_num_step_pres = window.app.steplistvalue('baina_num_step_pres');
                var baina_num_step_core = window.app.steplistvalue('baina_num_step_core');
				
				var buy_paras_name = window.app.steplistvalue('buy_paras_name');
				var buy_paras_value = window.app.steplistvalue('buy_paras_value');
				var buy_paras_icon = window.app.steplistvalue('buy_paras_icon');
				var buy_paras_nums = window.app.steplistvalue('buy_paras_nums');
				
				
                var maxnumbaina = $("input[name='maxnumbaina']").val();
				var paras_name = $("input[name='paras_name']").val();
                var baina_day_step = $("input[name='baina_day_step']").val();
                var ordertype_free = $("input[name='ordertype_free']").is(':checked'); //白拿
                var ordertype_void = $("input[name='ordertype_void']").is(':checked'); //空单
                var ordertype_buy = $("input[name='ordertype_buy']").is(':checked');
                var category = $("select[name='category']").val();
                if (parseInt(category) == 0) { $.error('请选择商品分类！'); return false; }
                if (!ordertype_free && !ordertype_void && !ordertype_buy) {
                    $("ul.switchs #s1").trigger("click");
					$.error('没有任何购买或投资方式');
					return false;
                }
				//组装规则参数
				var buy_paras = '';
				for (var i = 0, l = buy_paras_name.length; i < l; i++) {
                    if (buy_paras_name[i]!='') {
                        buy_paras += buy_paras_name[i] + ',' + buy_paras_value[i] + ',' + buy_paras_icon[i] + ',' + buy_paras_nums[i] + '|';
                    }
                }
				if(buy_paras.length>0 && paras_name.length<=0){ 
					$("ul.switchs #s2").trigger("click");
					$("input[name='paras_name']").focus();
					$.error('有设置规格参数，参数名称不能为空！'); 
					return false; 
				}
				$("input[name='buy_paras'").val(buy_paras);
                //组装直购数量优惠
                var buy_num_step = '';
                for (var i = 0, l = buy_num_step_nums.length; i < l; i++) {
                    if (parseInt(buy_num_step_nums[i]) > 0) {
                        buy_num_step += buy_num_step_nums[i] + ',' + buy_num_step_pres[i] + ',' + buy_num_step_core[i] + '|';
                    }
                }
                $("input[name='buy_num_step'").val(buy_num_step);
                //组装白拿优惠
                var baina_day_step = '';
                for (var i = 0, l = baina_day_step_nums.length; i < l; i++) {
                    if (parseInt(baina_day_step_nums[i]) > 0) {
                        baina_day_step += baina_day_step_nums[i] + ',' + baina_day_step_coin[i] + ',' + baina_day_step_pres[i] + ',' + baina_day_step_core[i] + '|';
                    }
                }
                $("input[name='baina_day_step'").val(baina_day_step);
                var baina_num_step = '';
                for (var i = 0, l = baina_num_step_nums.length; i < l; i++) {
                    if (parseInt(baina_num_step_nums[i]) > 0) {
                        baina_num_step += baina_num_step_nums[i] + ',' + baina_num_step_pres[i] + ',' + baina_num_step_core[i] + '|';
                    }
                }
                $("input[name='baina_num_step'").val(baina_num_step);
                if (parseInt(maxnumbaina) == 0 && $("input[name='baina_day_step'").length == 0 && ordertype_void) {
                    $("ul.switchs #s5").trigger("click");
					$.error('白领没有数量限制请设置优惠阶梯！');
                    return false;
                }
                //组装空单优惠
                var nil_day_step = '';
                for (var i = 0, l = nil_day_step_nums.length; i < l; i++) {
                    if (parseInt(nil_day_step_nums[i]) > 0) {
                        nil_day_step += nil_day_step_nums[i] + ',' + nil_day_step_coin[i] + ',' + nil_day_step_pres[i] + ',' + nil_day_step_core[i] + '|';
                    }
                }
                $("input[name='nil_day_step'").val(nil_day_step);
                var nil_num_step = '';
                for (var i = 0, l = nil_num_step_nums.length; i < l; i++) {
                    if (parseInt(nil_num_step_nums[i]) > 0) {
                        nil_num_step += nil_num_step_nums[i] + ',' + nil_num_step_pres[i] + ',' + nil_num_step_core[i] + '|';
                    }
                }
                $("input[name='nil_num_step'").val(nil_num_step);
                //return false;
                $(formid).submit();
            },
            //计算器
            price_Calculator_show: function() {
                $('#c_p').val($("input[name='price']").val());
                $('#priceCalculator').fadeIn(300);
            },
            price_Calculator_close: function() {
                $('#priceCalculator').fadeOut(300);
            },
            price_Calculator: function() {
                var c_p = $('#c_p').val(); //价格基数
                var c_d = $('#c_d').val(); //时长基数
                var c_r0 = $('#c_r0').val(); //利率基数
                var c_r1 = $('#c_r1').val(); //递增利率
                var c_cl = $('#c_cl').val(); //递增利率

                if (parseFloat(c_p) <= 0) { $.error('价格基数不正确'); return false; }
                if (parseFloat(c_d) <= 0) { $.error('上档日化利率需大于等于0'); return false; }
                if (parseFloat(c_r0) <= 0) { $.error('上档期限时长需大于等于0'); return false; }
                if (parseFloat(c_r1) <= 0) { $.error('本档期限时长需大于等于0'); return false; }
                if (c_cl.length <= 0) { $.error('计算档期不能为空，须用 , 从档期分隔'); return false; }

                var arr = c_cl.split(',');
                if (arr.length < 1) { $.error('计算档期不能为空，须用 , 从档期分隔'); };
                var vhtml = "";
                for (i = 0; i < arr.length; i++) {
                    var c_rate = parseFloat(c_r0) + (parseFloat(arr[i]) - parseFloat(c_d)) * parseFloat(c_r1);
                    var c_v = parseFloat(c_p) - (parseFloat(c_p) * parseFloat(c_rate) * parseFloat(arr[i]));
                    vhtml += arr[i] + "天，价格：" + c_v.toFixed(2) + "，利率：" + (c_rate * 100).toFixed(2) + " %<br />";
                }
                //日化利率
                $('#c_value').html(vhtml);

            },
            //比较查询日期
            date_diff: function(fromTime, toTime) {
                var date1 = fromTime;
                var date2 = toTime;
                var oDate1 = new Date(date1);
                var oDate2 = new Date(date2);
                if (oDate1.getTime() > oDate2.getTime()) {
                    return false;
                }
                return true;
            },
            //关闭弹出窗口
            closeDialogue: function() {
                var dialoguedisplay = $("#dialogue").is(":hidden");
                if (!dialoguedisplay) {
                    $('#dialogue').hide();
                }
                //$.dialogue({ close });
            },
            cash_confirm_save: function(obj) {

            },
			
			producticoncorp : function(_id){
				var imgFile = $("#"+_id).val();
				if(imgFile.length<=0 || imgFile=='#'){
					$.error('没有图片文件！');
					return false;
				}
				$.ajax({
					url: "/ajax/imgcorp",
					cache: false,
					data: {imgfile:imgFile},
					type: 'GET',
					dataType: 'html',
					success: function(data, textStatus, xhr) {
					    $("#iconiscorp").val(1);
						$.error(data);
					}
				});
			},
			producticoncorp_gg : function(objid){
				var imgFile = $("#paras_icon_"+objid).val();
				if(imgFile.length<=0 || imgFile=='#'){
					$.error('没有图片文件！');
					return false;
				}
				$.ajax({
					url: "/sys/imgcorp",
					cache: false,
					data: {imgfile:imgFile},
					type: 'GET',
					dataType: 'html',
					success: function(data, textStatus, xhr) {
						$.error(data);
					}
				});
			}
        }
});
//{{{ 通用复制函数

function CopyToClipboard(meintext, cb) {
    if (window.clipboardData) {
        window.clipboardData.setData("Text", meintext);
    } else if (window.netscape) {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var clip = Components.classes['@mozilla.org/widget/clipboard;1']
            .createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1']
            .createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"]
            .createInstance(Components.interfaces.nsISupportsString);
        var copytext = meintext;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
    } else {
        return false;
    }
    if (typeof cb == 'function') {
        return cb(meintext);
    } else {
        return true;
    }
}

function copy_code(copyText) {
    if (window.clipboardData) {
        window.clipboardData.setData("Text", copyText)
    } else {
        var flashcopier = 'flashcopier';
        if (!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="../_clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(copyText) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
    alert('复制成功，请直接粘贴！');
}

function cashTrue() {
    $('input.cashFalseSM').css('display', 'none');
}

function cashFalse() {
    $('input.cashFalseSM').css('display', '');
    var smval = $('input.cashFalseSM').val();
    if (smval.length <= 0) {
        $('input.cashFalseSM').val('提现失败！');
    }
}
function settrbg(){
	$(this).parent().parent().removeClass('notr');
	$(this).parent().html('--');
}
function set_order_state() {
    $(this).parent().parent().parent().find('span.statevalue').html('--');
    //console.log($(this).parent().parent().parent());
}
function closeParentWin(){
	window.parent.$.colorbox.close();
}
/*
* 数据提交
 */
function ajaxpostdata(_action,_data){
    //提交动作
    $.ajax({
        url: _action,
        cache: false,
        data: _data,//{ ids : _selectId },
        type: 'POST',
        dataType: 'text',
        error: function(xhr, textStatus, errThrow) {
            console.log(xhr);
        },
        success: function(data, textStatus, xhr) {
            $.dialogue(null);
            var error_message = xhr.getResponseHeader('X-Error-Message');
            if (error_message) {
                loadpage.close();
                if (error_message === 'dialogue') {
                    var obj = eval('(' + data + ')');;
                    $.dialogue(obj);
                } else {
                    $.error(decodeURIComponent(error_message));
                }
            }
        }
    });
}
function jsondata(_v){
	var func = _v.callback || function(){};
	$.ajax({
        url: _v.url,
        cache: _v.cache || false,
        data: _v.data,//{ ids : _selectId },
        type: _v.type || 'POST',
        dataType: _v.dataType || 'json',
		timeout: _v.timeout || 10000,
		async: _v.async || true,
		beforeSend:_v.beforeSend || function(){
			loadpage.loading.warp.text('正在加载，请稍后...');
			loadpage.loading.self.fadeIn(100);
		},
		complete: function(XMLHttpRequest, textStatus) {
			loadpage.loading.self.fadeOut(100);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
			$.error(XMLHttpRequest);
        },
        success: function(data, textStatus, xhr) {
            $.dialogue(null);
            var error_message = xhr.getResponseHeader('X-Error-Message');
            if (error_message) {
                loadpage.close();
                if (error_message === 'dialogue') {
                    var obj = eval('(' + data + ')');;
                    $.dialogue(obj);
                } else {
                    $.error(decodeURIComponent(error_message));
                }
            }else{
				func(data, textStatus, xhr);
			}
        }
    });
}
$(document).ready(function(e) {
    $(".colorbox").colorbox({ iframe: true,width:"100%",height:"100%" });
	$("#close_colorbox").on("click",function(){
		$.colorbox.close();	
	});
    $('.copy').live('click', function() {
        var $this = $(this);
        if ($this.is('[src]')) {
            CopyToClipboard($($this.attr('src')).val(), function() {
                alert('复制成功');
            });
        } else if ($this.is('[rel]')) {
            CopyToClipboard($this.attr('rel'), function() {
                alert('复制成功');
            });
        }
    });
	$("#changetopage").on("change",function(){
		var tourl = $(this).val();
		location.href = tourl;
	});
});